﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

public class ServerConfig
{
    public const byte ConnectPingByte = 3;

  
    public static string constDataDir => DataDir + "/Shared/Constant";

    public static string battleMapDataDir => DataDir + "/Shared/Map/Battle";

    public const string ServerNameKey = "name";
    public const string LogicPortForMasterKey = "logic_port_for_master";
    public const string LogicServerIPKey = "logic_server_ip";
    public const string BattleServerPortForLogicKey = "battle_port_for_logic";
    public const string BattleServerIPKey = "battle_server_ip";
    public const string MatchServerPortForLogicKey = "match_port_for_logic";
    public const string MatchServerIPKey = "match_server_ip";

    public const string LogicPortForClientKey = "logic_port_for_client";
    public const string BattlePortForClientKey = "battle_port_for_client";
    public const string ConnectPingPortKey = "connect_ping_port";

    public const bool UDPPaymentTestMode = false;
    public const bool GooglePaymentTestMode = false;
    public const bool ApplePaymentTestMode = false;

    public const string packageName = "com.feiya.chatsapp";

    //Match
    public const string npcNameListPath = "Match/Npc_Name.txt";

    //Master
    public static string gameVersionConfigDir => Path.Combine(configDir, "GameVersion");
    public static string gameVersionPath => Path.Combine(gameVersionConfigDir, "game_version.json");
    public static string whiteListPath => Path.Combine(configDir, "white_list.txt");

    public static string IpConfigPath => Path.Combine(configDir, "IpConfig.json");

    //public const string settingNoticePath = gameVersionDir + "/setting_notice.txt";

    public static string RSAPrivateKeyPath => Path.Combine(configDir,"RSA_PrivateKey.txt");

    const string masterServerUrl = "http://petsfight.com:5000/api/values";
    public const string KickOutUserUrl = masterServerUrl + "/kickoutuser";
    public const string KickOutAllUserUrl = masterServerUrl + "/kickoutalluser";
    public const string MasterInterfacePassword = "BycalGin@1992";

    //sql
    public const string MysqlPassword = "199296zhl";
    public const string DBShared = "app_shared";
    public const string DBUserBase = "app_user";
    public const string DBTexture= "app_texture";
    //public const string DBSharedRobot = "petsfight_shared_robot";
    //public const string DBUserRobot = "petsfight_user_robot";
    public const int MaxDBUserID = 10;
    public static string DBSharedSqlPath => DataDir + "/app_shared.sql";
    public static string DBSharedRobotSqlPath => DataDir + "/app_shared_robot.sql";
    public static string DBUserSqlPath => DataDir + "/app_user.sql";
    public static string DBRecreateUserSqlPath => DataDir + "/app_user_create.sql";

    //google
    public const string GooglePlayIAPClientId = "305983340334-lnckin9ejq174lv8v7olh28ttn6mvuug.apps.googleusercontent.com";
    public const string GooglePlayIAPClientSecret = "XKNPlEM-yWIj1qhRwMuzTvY_";
    public const string GooglePlayIAPRefreshToken = "1//0gqdCdpBD0HAGCgYIARAAGBASNwF-L9IrK87xY8sl305ItvyxoKv0D8c2KJvBJQs4c3NjKT9sLNP7OujO4u2uSaz9e3h8rL9ssgE"; 
    const string code = "4/4wGwqXZ0sce0tzHVvHkyoKcn_WPVqO41mVJcxTnu6cPVvJyT0U2vIRuZmt9XaUCWNcljlG6mAyUR__ihzqGQzls";

    //UDP
    public const string UDPIAPClientId = "4sH0oc71S5bbH9gSqG0VVg";
    public const string UDPIAPClientSecret = "ChiWqzxhQ8LkukD1IPGQ-dDvAtyayQ3Z5HnWnZfwPs4";

    public static string DataDir
    {
        get
        {
            if (AppContext.BaseDirectory.Contains("Publish"))
            {
                if (AppContext.BaseDirectory.Contains("Battle"))
                    return Path.Combine(AppContext.BaseDirectory, "../../../../../../Data");
                else
                    return Path.Combine(AppContext.BaseDirectory, "../../../../../Data");
            }
            else if (AppContext.BaseDirectory.Contains("net8.0"))
            {
                if (AppContext.BaseDirectory.Contains("Battle"))
                    return Path.Combine(AppContext.BaseDirectory, "../../../../../Data");
                else
                    return Path.Combine(AppContext.BaseDirectory, "../../../Data");
            }

            return Path.Combine(AppContext.BaseDirectory, "./Data");
        }
    }
    static string configDir
    {
        get
        {
            if (AppContext.BaseDirectory.Contains("Publish"))
            {
                if (AppContext.BaseDirectory.Contains("Battle"))
                    return Path.Combine(AppContext.BaseDirectory,"../../../../../../Config");
                else
                    return Path.Combine(AppContext.BaseDirectory, "../../../../../Config");
            }
            else if (AppContext.BaseDirectory.Contains("net8.0"))
            {
                if (AppContext.BaseDirectory.Contains("Battle"))
                    return Path.Combine(AppContext.BaseDirectory, "../../../../../Config");
                else
                    return Path.Combine(AppContext.BaseDirectory, "../../../Config");
            }

            return Path.Combine(AppContext.BaseDirectory, "/Config");
        }
    }

    public const string textureRelativePath = "Textures";// "Textures/Users";
    public static string textureDir
    {
        get
        {
            //if (AppContext.BaseDirectory.Contains("Publish"))
            //{
            //    return Path.Combine(AppContext.BaseDirectory, "../../../../Textures");
            //}
            //else if (AppContext.BaseDirectory.Contains("net8.0"))
            //{
            //    return Path.Combine(AppContext.BaseDirectory, "../../../Textures");
            //}
            return Path.Combine(AppContext.BaseDirectory, "../" + textureRelativePath);
        }
    }
    public const string momentPhotosRelativePath = "Textures/Moments";
    public static string momentPhotosDir 
    {
        get
        {
            return Path.Combine(AppContext.BaseDirectory, "../"+momentPhotosRelativePath);
        }
    }

    public const string domain = "hyloong.top";
    //public const string userTexDirUrl = $"{domain}/chatapp/{textureDirPath}";
    //public const string momentTexDirUrl = $"{domain}/chatapp/{momentPhotosDirPath}";
}

public class Server
{
    public string name;
    public string logicServerAddress;
    public int logicServerPortForMaster;
    public string matchServerAddress;
    public int matchServerPortForLogic;
    public string[] battleServerAddress;
    public int battleServerPortForLogic;
    public string walkServerAddress;
    public int walkServerPort;

    public int logicServerPortForClient;
    public int battleServerPortForClient;
    public int connectPingPort;

    public override string ToString()
    {
        return $"logicServerAddress:{logicServerAddress} logicServerPortForMaster:{logicServerPortForMaster}   logicServerPortForClient:{logicServerPortForClient}  battleServerPortForLogic:{battleServerPortForLogic} connectPingPort:{connectPingPort}";
    }

    public static Server ReadServerConfig()
    {
        try
        {
            string ipConfigStr = System.IO.File.ReadAllText(ServerConfig.IpConfigPath);
            //GameDebug.Log($"ipConfigStr:{ipConfigStr}");
            Dictionary<string, object> configDict = MiniJSON.Json.Deserialize(ipConfigStr) as Dictionary<string, object>;

            Server ipConfig = new Server()
            {
                name = configDict[ServerConfig.ServerNameKey].ToString(),

                logicServerAddress = configDict[ServerConfig.LogicServerIPKey].ToString(),
                logicServerPortForMaster = (int)(long)configDict[ServerConfig.LogicPortForMasterKey],

                matchServerAddress = configDict[ServerConfig.MatchServerIPKey].ToString(),
                matchServerPortForLogic = (int)(long)configDict[ServerConfig.MatchServerPortForLogicKey],

                battleServerAddress = ((List<object>)configDict[ServerConfig.BattleServerIPKey]).Map(e=>(string)e).AsArray(),
                battleServerPortForLogic = (int)(long)configDict[ServerConfig.BattleServerPortForLogicKey],

                logicServerPortForClient = (int)(long)(configDict[ServerConfig.LogicPortForClientKey]),
                battleServerPortForClient = (int)(long)(configDict[ServerConfig.BattlePortForClientKey]),
                connectPingPort = (int)(long)configDict[ServerConfig.ConnectPingPortKey],
            };
            GameDebug.Log($"读取配置文件成功:{ipConfig}");

            if (string.IsNullOrEmpty(ipConfig.logicServerAddress))
            {
                ipConfig.logicServerAddress = GetLocalIP();

                GameDebug.Log($"Logic 使用本地IP:{ipConfig.logicServerAddress}  port:{ipConfig.logicServerPortForClient}");
            }

            //if (string.IsNullOrEmpty(ipConfig.logicServerAddress))
            //{
            //    ipConfig.logicServerAddress = ipConfig.matchServerAddress = GetLocalIP();

            //    GameDebug.Log($"使用本地IP:{ipConfig.matchServerAddress}");
            //}
            //for (int i=0;i< ipConfig.battleServerAddress.Length;i++)
            //{
            //    if (string.IsNullOrEmpty(ipConfig.battleServerAddress[i]))
            //    {
            //        ipConfig.battleServerAddress[i] =  GetLocalIP();

            //        GameDebug.Log($"戰鬥服使用本地IP:{ipConfig.battleServerAddress[i]}");
            //    }
            //}
            return ipConfig;
        }
        catch (Exception e)
        {
            GameDebug.LogError("读取配置文件出错");
            GameDebug.LogError(e?.Message+"\n"+e.StackTrace);

            return Server.GetDefault();
        }
    }

    public static string GetLocalIP()
    {
        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[ipHostInfo.AddressList.Length - 1];
        string ipStr = "";
        ipHostInfo.AddressList.ForEach(e =>
        {
            if (e.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
            {
                ipStr = e.ToString();
            }
             GameDebug.Log($"Address  AddressFamily:{e.AddressFamily}  str:{e.ToString()}");
        });
        return ipStr;
    }
 
    static Server GetDefault()
    {
        string ipStr = GetLocalIP();

        return new Server()
        {
            name = "测试服",

            logicServerAddress = ipStr,
            logicServerPortForMaster = 1556,

            battleServerAddress = new string[] { ipStr },
            battleServerPortForLogic = 1577,

            matchServerAddress = ipStr,
            matchServerPortForLogic = 1564,

            logicServerPortForClient = 1555,
            battleServerPortForClient = 1576,
            connectPingPort = 1579
        }; 
    }

    //static void TestGenConfigJson()
    //{
    //    System.Collections.Generic.Dictionary<string, string> ipConfig = new System.Collections.Generic.Dictionary<string, string>();


    //    ipConfig[ServerConfig.LogicPortForMasterKey] = ServerConfig.LogicServerPortForMaster.ToString();
    //    ipConfig[ServerConfig.LogicServerIPKey] = ServerConfig.LogicServerIP;

    //    ipConfig[ServerConfig.BattleServerPortForLogicKey] = ServerConfig.BattleServerPortForLogic.ToString();
    //    ipConfig[ServerConfig.BattleServerIPKey] = ServerConfig.BattleServerIP;

    //    ipConfig[ServerConfig.MatchServerPortForLogicKey] = ServerConfig.MatchServerPortForLogic.ToString();
    //    ipConfig[ServerConfig.MatchServerIPKey] = ServerConfig.MatchServerIP;

    //    //Server server = new Server();
    //    //server.name = "测试服";
    //    //server.logicServerPortForMaster = ServerConfig.LogicServerPortForMaster;
    //    //server.logicServerAddress = ServerConfig.LogicServerIP;

    //    //server.battleServerPortForLogic = ServerConfig.BattleServerPortForLogic;
    //    //server.battleServerAddress = ServerConfig.BattleServerIP;

    //    //server.matchServerPortForLogic = ServerConfig.MatchServerPortForLogic;
    //    //server.matchServerAddress = ServerConfig.MatchServerIP;

    //    string serverStr = MiniJSON.Json.Serialize(ipConfig);

    //    Console.WriteLine($"serverStr:{serverStr}");

    //}
}